import { DICT_KEY } from "@/enums/cacheEnum";
import { createLocalStorage } from "@/utils/cache";
import { listSimpleDictData } from "@/api/system/dict/data";
import { DictDataVO } from "@/api/system/dict/types";

const ls = createLocalStorage();

/** DictState */
export interface DictState {
	dictMap: Map<string, any>;
	isSetDict: boolean;
}

export default function useDictCache() {
	const dictState: DictState = {
		dictMap: new Map<string, any>(),
		isSetDict: false
	};

	const getDictMap = () => {
		const dictMap = ls.get(DICT_KEY);
		if (dictMap) dictState.dictMap = dictMap;
		return dictState.dictMap;
	};

	const setDictMap = async () => {
		const dictMap = ls.get(DICT_KEY);
		if (dictMap) {
			dictState.dictMap = dictMap;
			dictState.isSetDict = true;
		} else {
			const res = await listSimpleDictData();
			// 设置数据
			const dictDataMap = new Map<string, any>();
			res.forEach((dictData: DictDataVO) => {
				// 获得 dictType 层级
				const enumValueObj = dictDataMap[dictData.dictType];
				if (!enumValueObj) dictDataMap[dictData.dictType] = [];

				// 处理 dictValue 层级
				dictDataMap[dictData.dictType].push({
					value: dictData.value,
					label: dictData.label,
					colorType: dictData.colorType,
					cssClass: dictData.cssClass
				});
			});
			dictState.dictMap = dictMap;
			dictState.isSetDict = true;
			ls.set(DICT_KEY, dictDataMap, 60); // 60 秒 过期
		}
	};

	return {
		dictState,
		getDictMap,
		setDictMap
	};
}
